import { ref } from "vue";
import { defineStore } from "pinia";
import { accountLoginAPI, fetchTaskReportInfoAPI, fetchTruckInfoAPI, fetchUserInfoAPI, mobileLoginAPI, sendCodeAPI } from "@/api/userApi";
import { clearToken, getToken, setToken } from "@/utils/storage";

const useUserStore = defineStore("userStore", () => {
  /*用户登录后存储的token*/
  const token = ref(getToken() || "");
  /*用户信息*/
  const userInfo = ref({});
  /*车辆信息*/
  const truckInfo = ref({});
  /*任务信息*/
  const taskReportInfo = ref({});
  /*账号登录的请求函数*/
  const accountLogin = async (formData) => {
    const { data } = await accountLoginAPI(formData);
    token.value = data;
    setToken(data);
  };

  /*发送验证码的请求函数*/
  const sendCode = async (params) => {
    const { data } = await sendCodeAPI(params);
    return data.code;
  };

  /*手机号登录的请求函数*/
  const mobileLogin = async (formData) => {
    const { data } = await mobileLoginAPI(formData);
    token.value = data.token;
    setToken(data.token);
  };

  /*获取用户信息的请求函数*/
  const fetchUserInfo = async () => {
    const { data } = await fetchUserInfoAPI();
    userInfo.value = data;
  };

  /*获取车辆信息的请求函数*/
  const fetchTruckInfo = async () => {
    const { data } = await fetchTruckInfoAPI();
    truckInfo.value = data;
  };

  /*获取任务信息的请求函数*/
  const fetchTaskReportInfo = async (params) => {
    const { data } = await fetchTaskReportInfoAPI(params);
    taskReportInfo.value = data;
  };
  /*退出登录的函数*/
  const logout = () => {
    token.value = "";
    clearToken();
  };

  return {
    token,
    userInfo,
    truckInfo,
    taskReportInfo,
    accountLogin,
    sendCode,
    mobileLogin,
    logout,
    fetchUserInfo,
    fetchTruckInfo,
    fetchTaskReportInfo
  };

});


export default useUserStore;
